package com.wqj.kyee.gps.nav

import android.annotation.SuppressLint
import android.app.ActivityOptions
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.Log
import android.view.*
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.amap.api.maps.*
import com.amap.api.maps.model.*
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.*
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.route.*
import com.sothree.slidinguppanel.SlidingUpPanelLayout
import com.wqj.kyee.gps.CarInfoDialog
import com.wqj.kyee.gps.R
import com.wqj.kyee.gps.adapter.CustomLocationAdapter
import com.wqj.kyee.gps.bluetooth.PotListAdapter
import com.wqj.kyee.gps.nav.overlay.DrivingRouteOverlay
import com.wqj.kyee.gps.nav.overlay.PoiOverlay
import com.wqj.kyee.gps.nmea.NMEA
import com.wqj.kyee.gps.service.NMEAParserService
import com.wqj.kyee.gps.ui.BasePopupWindow
import com.wqj.kyee.gps.ui.SearchActivity
import com.wqj.kyee.gps.util.*
import kotlinx.android.synthetic.main.sliding_up.*
import org.jetbrains.anko.find
import java.lang.ref.WeakReference
import java.text.DecimalFormat


class MapActivity : AppCompatActivity(), View.OnClickListener, RouteSearch.OnRouteSearchListener
        ,GeocodeSearch.OnGeocodeSearchListener, TextView.OnEditorActionListener
        , PoiSearch.OnPoiSearchListener, LoadMoreListView.OnLoadMoreListener
        , SlidingUpPanelLayout.PanelSlideListener, AMap.OnPOIClickListener, AMap.OnMarkerClickListener
        , ViewTreeObserver.OnGlobalLayoutListener, AMap.OnMapTouchListener
        , CompoundButton.OnCheckedChangeListener, AMap.OnCameraChangeListener, NMEAParserService.OnInfoUpdateListener {

    /*
    override fun readInfo(gpsPosition: NMEA.GPSPosition?) {
        android.util.Log.e(TAG, gpsPosition.toString());
        if (gpsPosition != null) {
            onMyLocationChanged(gpsPosition.lat, gpsPosition.lon)
        }
    }
    */

    val TAG: String = "MapActivity"
    var poiCurrentPage: Int = 1
    var mDriveRouteResult: DriveRouteResult? = null
    var loadingDialog: MyLoadingDialog = MyLoadingDialog()
    var carInfoDialog: CarInfoDialog = CarInfoDialog()
    lateinit var query: PoiSearch.Query
    lateinit var geocoderSearch:GeocodeSearch
    lateinit var mMapView: MapView
    lateinit var routeSearchBtn: ImageButton
    lateinit var potSearchText: EditText
    lateinit var listView: LoadMoreListView
    lateinit var listAdapter: PotListAdapter
    lateinit var routeSearch: RouteSearch
    lateinit var poiResult: PoiResult
    lateinit var aMap: AMap
    lateinit var slidingTitle: TextView
    lateinit var searchLayout: LinearLayout
    //lateinit var btReadThread: BtReadThread
    lateinit var ivCurrentLoc : ImageButton
    lateinit var mMapUiSettings : UiSettings
    var mapHeight: Int = 0

    var locationMarker : Marker? = null
    var projection : Projection? = null

    var useMoveToLocationWithMapMode = true
    lateinit var myCancelCallback : MyCancelCallback

    lateinit var mRoadConditinCb : CheckBox
    lateinit var mZoomInBtn : ImageButton
    lateinit var mZoomOutBtn : ImageButton
    lateinit var mShowCustomLocationBtn : ImageButton

    lateinit var mOfflineSetting : ImageButton

    lateinit var mContext : Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.sliding_up)

        supportActionBar?.hide()

        mContext = this

        mMapView = find<MapView>(R.id.map)
        routeSearchBtn = find(R.id.routeSearch)
        potSearchText = find(R.id.potSearchText)
        slidingTitle = find(R.id.title)
        searchLayout = find(R.id.searchLayout)
        listView = find(R.id.list)

        ivCurrentLoc = find(R.id.id_iv_currentLocation)
        mShowCustomLocationBtn = find(R.id.id_ib_setLocation)

        mRoadConditinCb = find(R.id.id_cb_road_condition)
        mZoomInBtn = find(R.id.id_btn_zoom_in)
        mZoomOutBtn = find(R.id.id_btn_zoom_out)
        mOfflineSetting = find(R.id.id_btn_offline_setting)

        mMapView.onCreate(savedInstanceState);

        //初始化地图控制器对象
        aMap = mMapView.getMap()
        mMapUiSettings = aMap.uiSettings
        aMap.setOnPOIClickListener(this)
        aMap.setOnMarkerClickListener(this)
        aMap.setOnCameraChangeListener(this)


        routeSearch = RouteSearch(this)
        geocoderSearch = GeocodeSearch(this)
        setListener()
        initMapStyle()
        // 设置位置信息回调
        setLocationChangeCallback()
        // 从bt gps板读取位置数据
        sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN)
        potlistAdapter = PotListAdapter(poiItemList, this)
        sliding_layout.addPanelSlideListener(this)

        myCancelCallback = MyCancelCallback(this)
        //btReadThread = BtReadThread(MyHandler(this))
    }

    fun setListener() {
        map.getViewTreeObserver().addOnGlobalLayoutListener(this)
        carInfo.setOnClickListener(this)
        routeSearchBtn.setOnClickListener(this)
        potSearchText.setOnEditorActionListener(this)
        routeSearch.setRouteSearchListener(this)
        geocoderSearch.setOnGeocodeSearchListener(this)
        listView.setONLoadMoreListener(this)
        listView.setOnItemClickListener(object : AdapterView.OnItemClickListener {

            override fun onItemClick(arg0: AdapterView<*>, arg1: View?, arg2: Int,
                                     arg3: Long) {
                Log.i("wqj", "id: " + arg2)
                useMoveToLocationWithMapMode = false
                var item = poiItemList[arg2]
                // BtClientThread(discoveredBTDevices[arg2], mHandler).start()
                var lat = item.latLonPoint.latitude
                var lng = item.latLonPoint.longitude
                var latLng = LatLng(lat, lng)
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 19f))

                var distance = AMapUtils.calculateLineDistance(LatLng(curLat, curLng) , latLng) / 1000f
                var df = DecimalFormat("#.00")
                var markerOption = MarkerOptions().icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                        .position(latLng)
                        .title(item.title)
                        .snippet("距离: " + df.format(distance) + "公里")
                        .draggable(true)
                var marker = aMap.addMarker(markerOption)
                marker.showInfoWindow()
            }

        })

        restrictionFlag.setOnCheckedChangeListener(object: CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(p0: CompoundButton?, p1: Boolean) {
                isRestrict = p1
                Log.d("wqj", "躲避限行: " + p1)
            }

        })

        ivCurrentLoc.setOnClickListener(this)
        potSearchText.setOnClickListener(this)

        mShowCustomLocationBtn.setOnClickListener(this)

        mRoadConditinCb.setOnCheckedChangeListener(this)
        mZoomOutBtn.setOnClickListener(this)
        mZoomInBtn.setOnClickListener(this)
        mOfflineSetting.setOnClickListener(this)
        id_iv_offline_map.setOnClickListener(this)
    }

    fun onBackClick(view: View) {
        this.finish()
    }

    fun initMapStyle() {
        val myLocationStyle = MyLocationStyle()
        // 只定位一次且定位到中心点
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE)
        //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle)
        // 设置默认定位按钮是否显示，非必需设置。
        // mUiSettings.setMyLocationButtonEnabled(true)
        initMapUi(aMap.getUiSettings())
        // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //aMap.setMyLocationEnabled(true)
        // aMap.setTrafficEnabled(true)

        mMapUiSettings.isScaleControlsEnabled = true
        //mMapUiSettings.isCompassEnabled = true
        //mMapUiSettings.isZoomControlsEnabled = true
        //mMapUiSettings.zoomPosition = AMapOptions.ZOOM_POSITION_RIGHT_CENTER

        mMapUiSettings.isTiltGesturesEnabled = true
        mMapUiSettings.isRotateGesturesEnabled = true

        mMapUiSettings.logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_CENTER

        aMap.setOnMapTouchListener(this)


        var tiltUpdate = CameraUpdateFactory.changeTilt(30F)
        aMap.moveCamera(tiltUpdate)

        aMap.clear();
        //aMap.addMarker(MarkerOptions().position(LatLng(curLat, curLng))
        //        .icon(BitmapDescriptorFactory.fromResource(R.drawable.gps_point))
        //        .anchor(0.5f, 0.5f))

        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(curLat, curLng), 15f))
    }

    fun setLocationChangeCallback() {
        // 位置信息回调
        aMap.setOnMyLocationChangeListener { location -> Unit
            Log.d(TAG, "wqj: " + location.latitude)
        }
    }

    class MyCancelCallback(activity : MapActivity) : AMap.CancelableCallback {

        private val mActivity: WeakReference<MapActivity>
        init {
            mActivity = WeakReference<MapActivity>(activity)
        }

        lateinit var targetLatLng : LatLng

        fun setTartgetLatlng(latlng : LatLng) {
            targetLatLng = latlng
        }

        override fun onFinish() {
            val activity = mActivity.get()

            if (activity != null) {
                if ((activity.locationMarker != null) && (targetLatLng != null)) {
                    activity.locationMarker!!.position = targetLatLng
                }
            }
        }

        override fun onCancel() {
            val activity = mActivity.get()
            if (activity != null) {
                if ((activity.locationMarker != null) && (targetLatLng != null)) {
                    activity.locationMarker!!.position = targetLatLng
                }
            }
        }

    }

    fun startMoveLocationAndMap(latLng : LatLng) {
        if (projection == null) {
            projection = aMap.projection;
        }

        if (locationMarker != null && projection != null) {
            var markerLocation = locationMarker!!.position
            var screenPosition = aMap.projection.toScreenLocation(markerLocation)
            locationMarker!!.setPositionByPixels(screenPosition.x, screenPosition.y)
        }

        myCancelCallback.setTartgetLatlng(latLng)

        aMap.animateCamera(CameraUpdateFactory.changeLatLng(latLng), 500, myCancelCallback)
    }

    fun startChangeLocation(latLng : LatLng) {
        if (locationMarker != null) {
            var curLatLng = locationMarker!!.position
            if (curLatLng == null || !curLatLng.equals(latLng)) {
                locationMarker!!.position = latLng;
            }
        }
    }

    private var counter4CityQuery : Int = 0
    fun onMyLocationChanged(lat: Double, lng: Double) { //Parameters are GPS Coordinate

        var currLatLng = UnitConverter.GPS2AMap(applicationContext, LatLng(lat, lng))

        curLat = currLatLng.latitude
        curLng = currLatLng.longitude

        // 获得当前所在城市信息
        counter4CityQuery++
        if (counter4CityQuery == 30) {
            getAddress(curLat, curLng)
            counter4CityQuery = 0
        }

        if (locationMarker == null) {  // First location
            //aMap.clear()
            var cu = CameraUpdateFactory.changeLatLng(currLatLng)
            locationMarker = aMap.addMarker(MarkerOptions().position(currLatLng)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.gps_point))
                    .anchor(0.5f, 0.5f))

            aMap.animateCamera(cu, 800, null)
        } else {
            if (useMoveToLocationWithMapMode) {
                startMoveLocationAndMap(currLatLng)
            } else {
                startChangeLocation(currLatLng)
            }
        }
    }

    override fun onCameraChangeFinish(p0: CameraPosition?) {
        var currentZoom = p0!!.zoom

        if (currentZoom >= 19.0f) {
            mZoomInBtn.isEnabled = false
        } else {
            mZoomInBtn.isEnabled =  true
        }

        if (currentZoom <= 3.0f) {
            mZoomOutBtn.isEnabled = false
        } else {
            mZoomOutBtn.isEnabled = true
        }
    }

    override fun onCameraChange(p0: CameraPosition?) {

    }

    override fun onTouch(p0: MotionEvent?) {
        super.onTouchEvent(p0)
        Log.e(TAG,"onTouch 关闭地图和小蓝点一起移动的模式");
        useMoveToLocationWithMapMode = false
    }

    override fun onGlobalLayout() {
//        Log.d("wqj", "layout changed: " + map.height)
//        var currHeight = map.height
//
//        if (mapHeight == 0) {
//            mapHeight = currHeight
//            return
//        }
//        if (currHeight < mapHeight) {
//            //Handler().postDelayed({
//                EnterPotEditMode(true)
//            //}, 100)
//
//        } else {
//            Handler().postDelayed({
//                EnterPotEditMode(false)
//            }, 200)
//
//        }

    }

//    public class MyHandler(activity: MapActivity) : Handler() {
//
//        //对Activity的弱引用
//        private val mActivity: WeakReference<MapActivity>
//        init {
//            mActivity = WeakReference<MapActivity>(activity)
//        }
//        override fun handleMessage(msg: Message) {
//            val activity = mActivity.get()
//            if (activity == null) {
//                super.handleMessage(msg)
//                return
//            }
//            when (msg.what) {
//                BtDevicesActivity.GPS_BOARD_DATA -> {
//                    var data: NMEA.GPSPosition = msg.obj as NMEA.GPSPosition
//                    //var content = MainActivity.ByteArrayToHexString(data.buffer, data.size)
//                    //var text = "获取到蓝牙板数据: " + content
//                    //Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
//                    // 读取gps板定位数据并显示在地图上
//                    activity.onMyLocationChanged(data.lat, data.lon)
//                }
//                else -> super.handleMessage(msg)
//            }
//        }
//    }


    var poiMarker : Marker? = null
    var selectedPoi : Poi? = null
    override fun onPOIClick(p0: Poi?) {

//        if (poiMarker != null) {
//            poiMarker!!.remove()
//        }

        if (selectedPoi != null) {
            if (selectedPoi!!.equals(p0)) {
                return
            }
        }

        selectedPoi = p0
        //var markOptions = MarkerOptions()
       // markOptions.position(p0?.coordinate)
        //var textView = TextView(applicationContext)
        //textView.setText(p0?.name)
        //textView.gravity = Gravity.CENTER
        //textView.setBackgroundResource(R.drawable.custom_info_bubble)

//        var view = layoutInflater.inflate(R.layout.poikeywordsearch_uri, null)
//        view?.setBackgroundResource(R.drawable.custom_info_bubble)
//        var title = view?.findViewById<TextView>(R.id.title)
//        title?.text = p0?.name
//
//        markOptions.icon(BitmapDescriptorFactory.fromView(view))
//        poiMarker = aMap.addMarker(markOptions)

        if (!TextUtils.isEmpty(selectedPoi?.getPoiId())) {
            val query = PoiSearch.Query(selectedPoi?.getName(), "", curCity)
            query.isDistanceSort = false
            query.requireSubPois(true)
            val poiSearch = PoiSearch(applicationContext, query)
            poiSearch.setOnPoiSearchListener(this)
            poiSearch.searchPOIIdAsyn(selectedPoi?.getPoiId())
        }

    }

    override fun onMarkerClick(p0: Marker?): Boolean {

        if (p0?.equals(poiMarker)!!) {
            startActivity(startIntent)
        }

        return false
    }

    override fun onCheckedChanged(p0: CompoundButton?, p1: Boolean) {
        when (p0?.id) {
            R.id.id_cb_road_condition -> {
                aMap.isTrafficEnabled = p1

                if (p1) {
                    ToastUtil.show(applicationContext, "开启并更新实时路况")
                } else {
                    ToastUtil.show(applicationContext, "关闭实时路况")
                }
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.routeSearch -> {
            // fromAndTo包含路径规划的起点和终点，drivingMode表示驾车模式
            // 第三个参数表示途经点（最多支持16个），第四个参数表示避让区域（最多支持32个），第五个参数表示避让道路
                /*
                val mStartPoint = LatLonPoint(39.942295, 116.335891)//起点，39.942295,116.335891
                val mEndPoint = LatLonPoint(39.995576, 116.481288)//终点，39.995576,116.481288
                var fromAndTo = RouteSearch.FromAndTo(mStartPoint, mEndPoint)
                val query = DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null, null, "")
                routeSearch.calculateDriveRouteAsyn(query)
                */
                //startActivity<RouteSelectActivity>()
                var intent =  Intent(this, RouteShowActivity::class.java)
                intent.putExtra(Constants.EXTRA_CURRENT_LAT, curLat)
                intent.putExtra(Constants.EXTRA_CURRENT_LNG, curLng)
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, curCity)
                startActivity(intent)
            }
            R.id.id_iv_currentLocation -> {
                var cu =  CameraUpdateFactory.changeLatLng(LatLng(curLat, curLng))
                aMap.animateCamera(cu, 500, null)
                useMoveToLocationWithMapMode = true
            }
            R.id.carInfo -> {
                carInfoDialog?.show(getFragmentManager(), "车牌号码")
            }
            R.id.potSearchText -> {
                // EnterPotEditMode(true)
                //val intent = Intent(this, SearchActivity::class.java)
                //startActivity(intent)
                var intent = Intent(this, SearchActivity::class.java)
                intent.putExtra(BaseTransitionInActivity.EXTRA_TRANSITION, BaseTransitionInActivity.TRANSITION_FADE_FAST)
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, curCity)
                startActivityWithOptions(intent)
            }

            R.id.id_btn_zoom_in  -> {
                aMap.animateCamera(CameraUpdateFactory.zoomIn(), 500, null)
            }

            R.id.id_btn_zoom_out -> {
                aMap.animateCamera(CameraUpdateFactory.zoomOut(), 500, null)
            }

            R.id.id_btn_offline_setting -> {
                startActivity(Intent(this.applicationContext,
                        com.amap.api.maps.offlinemap.OfflineMapActivity::class.java))
            }

            R.id.id_iv_offline_map -> {
                startActivity(Intent(this.applicationContext,
                        com.amap.api.maps.offlinemap.OfflineMapActivity::class.java))
            }

            R.id.id_ib_setLocation -> {
                initPopWindow()
            }
        }
    }

    fun getCurrentCity() : String {
        return curCity
    }

    fun getCurrentLat() : Double {
        return curLat
    }

    fun getCurrentLng() : Double {
        return curLng
    }

    lateinit var mCustomLocAdapter : CustomLocationAdapter
    lateinit var mCustomLocList : MutableList<String>
    fun loadCustomLocation() {
        mCustomLocList = ArrayList()

        var sp = getSharedPreferences(Constants.CustomLocation_Preferences, Context.MODE_PRIVATE)

        var item1 = sp.getString(Constants.SP_KEY_LOCATION_HOME, "")
        if (!item1.isEmpty()) {
            item1 = "家" + Constants.FIELD_SEPARATOR + item1
        } else {
            item1 = "家" + Constants.FIELD_SEPARATOR + Constants.FIELD_SEPARATOR
        }
        mCustomLocList.add(item1)

        var item2 = sp.getString(Constants.SP_KEY_LOCATION_COMPANY, "")
        if (!item2.isEmpty()) {
            item2 = "公司" + Constants.FIELD_SEPARATOR + item2
        } else {
            item2 = "公司" + Constants.FIELD_SEPARATOR + Constants.FIELD_SEPARATOR
        }
        mCustomLocList.add(item2)

        mCustomLocAdapter = CustomLocationAdapter(this, mCustomLocList)
        mCustomLocAdapter.notifyDataSetChanged()
    }


    fun initPopWindow() {
        var contentView : View
        var window : BasePopupWindow
        var customListView : ListView
        var location : IntArray = kotlin.IntArray(2)
        var contentHeight : Int

        var wm : WindowManager
        var outMetrics = DisplayMetrics()

        wm = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        wm.defaultDisplay.getMetrics(outMetrics)


        contentView = LayoutInflater.from(applicationContext).inflate(R.layout.popupwindow_content, null)

        window = BasePopupWindow(this)
        window.width = 3 * outMetrics.widthPixels / 5
        window.contentView = contentView

        customListView = contentView.findViewById<ListView>(R.id.id_lv_customListView)
        loadCustomLocation()

        customListView.adapter = mCustomLocAdapter


        contentHeight = window.contentView.measuredHeight

        mShowCustomLocationBtn.getLocationOnScreen(location)
        window.showAtLocation(mShowCustomLocationBtn, Gravity.NO_GRAVITY, outMetrics.widthPixels - window.width - 20 , location[1] - mShowCustomLocationBtn.height * 2)
    }

    @SuppressLint("RestrictedApi")
    fun startActivityWithOptions(intent : Intent) {
        var transitionActivity = ActivityOptions.makeSceneTransitionAnimation(this);
        //startActivity(intent, transitionActivity.toBundle())
        startActivityForResult(intent, Constants.SEARCH_REQUEST_CODE, transitionActivity.toBundle())
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == Constants.SEARCH_REQUEST_CODE) {
            if (resultCode == Constants.SEARCH_RESULT_CODE) {
                var keyword = data?.getStringExtra(Constants.EXTRA_KEYWORD)

                doSearchQuery(keyword!!, false)
                potSearchText.setText(keyword)
            }
            else if (resultCode == Constants.SEARCH_ARROUND_RESULT_CODE) {
                var keyword = data?.getStringExtra(Constants.EXTRA_KEYWORD)

                doSearchQuery(keyword!!, true)
                potSearchText.setText(keyword)
            }
        }

        if (resultCode == Constants.SEARCH_LOCATION_RESULT_CODE) {

            if (requestCode == Constants.SEARCH_REQUSET_HOME_CODE) {

                var item = data?.getParcelableExtra<PoiItem>(Constants.EXTRA_POIITEM)
                var content = ""

                content += item?.title + Constants.FIELD_SEPARATOR + item?.latLonPoint.toString()

                var sp = getSharedPreferences(Constants.CustomLocation_Preferences, Context.MODE_PRIVATE)
                var editor = sp.edit()

                editor.putString(Constants.SP_KEY_LOCATION_HOME, content)
                editor.commit()

                loadCustomLocation()


            } else if (requestCode == Constants.SEARCH_REQUEST_COMPANY_CODE) {

                var item = data?.getParcelableExtra<PoiItem>(Constants.EXTRA_POIITEM)
                var content = ""

                content += item?.title + Constants.FIELD_SEPARATOR + item?.latLonPoint.toString()

                var sp = getSharedPreferences(Constants.CustomLocation_Preferences, Context.MODE_PRIVATE)
                var editor = sp.edit()

                editor.putString(Constants.SP_KEY_LOCATION_COMPANY, content)
                editor.commit()

                loadCustomLocation()
            }
        }
    }

    override fun onPanelSlide(panel: View?, slideOffset: Float) {
        Log.d("top123", "state: " + slideOffset)
    }

    override fun onPanelStateChanged(panel: View?, previousState: SlidingUpPanelLayout.PanelState?, newState: SlidingUpPanelLayout.PanelState?) {
        Log.d("top123", "state: " + newState)
        when (newState) {
            SlidingUpPanelLayout.PanelState.COLLAPSED -> {
                slidingTitle.setText("查看更多")
                searchLayout.visibility = View.VISIBLE
            }
            else -> {
                slidingTitle.setText("收起")
                searchLayout.visibility = View.GONE
            }
        }
    }

    override fun onDriveRouteSearched(result: DriveRouteResult?, errorCode: Int) {
        aMap.clear()
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size > 0) {
                    mDriveRouteResult = result
                    val drivePath = mDriveRouteResult?.getPaths()?.get(0)
                    val drivingRouteOverlay = DrivingRouteOverlay(
                            this, aMap, drivePath,
                            mDriveRouteResult?.getStartPos(),
                            mDriveRouteResult?.getTargetPos(), null)
                    drivingRouteOverlay.setNodeIconVisibility(false)//设置节点marker是否显示
                    // drivingRouteOverlay.setIsColorfulline(true)//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap()
                    drivingRouteOverlay.addToMap()
                    drivingRouteOverlay.zoomToSpan()
                    // mBottomLayout.setVisibility(View.VISIBLE)
                    val dis = drivePath?.getDistance()?.toInt()
                    val dur = drivePath?.getDuration()?.toInt()
                    val des = AMapUtil.getFriendlyTime(dur!!) + "(" + AMapUtil.getFriendlyLength(dis!!) + ")"
                    Log.d(TAG, "wqj: 耗时： " + des)
                    ToastUtil.show(this, "wqj: 耗时： " + des)
                   // mRotueTimeDes.setText(des)
                   // mRouteDetailDes.setVisibility(View.VISIBLE)
                    val taxiCost = mDriveRouteResult?.getTaxiCost()?.toInt()
                   // mRouteDetailDes.setText("打车约" + taxiCost + "元")
                    /*
                    mBottomLayout.setOnClickListener(View.OnClickListener {
                       // val intent = Intent(mContext,
                       //         DriveRouteDetailActivity::class.java)
                        intent.putExtra("drive_path", drivePath)
                        intent.putExtra("drive_result",
                                mDriveRouteResult)
                        startActivity(intent)

                    })
                    */

                } else if (result != null && result.getPaths() == null) {
                    //ToastUtil.show(this, R.string.no_result)
                }

            } else {
                //ToastUtil.show(this, R.string.no_result)
            }
        } else {
           // ToastUtil.showerror(this, errorCode)
        }

    }

    override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onGeocodeSearched(result: GeocodeResult?, rCode: Int) {
        dismissDialog()
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size > 0) {
                //listView.setAdapter(PotListAdapter(result.getGeocodeAddressList(), this))
                val address = result.getGeocodeAddressList().get(0)
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        AMapUtil.convertToLatLng(address.getLatLonPoint()), 10f))
                val geoMarker = aMap.addMarker(MarkerOptions().anchor(0.5f, 0.5f)
                        .icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_RED)))
                geoMarker.setPosition(AMapUtil.convertToLatLng(address
                        .getLatLonPoint()))
                val addressName = ("经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
                        + address.getFormatAddress())
                ToastUtil.show(this@MapActivity, addressName)
            } else {
                ToastUtil.show(this@MapActivity, R.string.no_result)
            }
        } else {
            ToastUtil.showerror(this, rCode)
        }
        dismissDialog()
    }

    override fun onRegeocodeSearched(result: RegeocodeResult?, rCode: Int) {
        //dismissDialog();
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                // curCity = result.getRegeocodeAddress().getFormatAddress()
                curCity = result.regeocodeAddress.cityCode
                Log.d("wqj", "current city: " + curCity)
            } else {
                ToastUtil.show(this, R.string.no_result);
            }
        } else {
            ToastUtil.showerror(this, rCode);
        }
    }



    // start --- POI 检索回调
     var startIntent : Intent? = null
    override fun onPoiItemSearched(poiItem: PoiItem?, errorCode: Int) {

        if (poiMarker != null) {
            poiMarker!!.remove()
        }

        var view = layoutInflater.inflate(R.layout.poikeywordsearch_uri, null)
        var title = view?.findViewById<TextView>(R.id.title)
        var markOptions = MarkerOptions()

        var  intent = Intent(this, RouteShowActivity::class.java)

        var route_show_btn = view?.findViewById<ImageButton>(R.id.start_route_show)

        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (poiItem != null) {

                var targetLatLng = AMapUtil.convertToLatLng(poiItem.latLonPoint)
                markOptions.position(targetLatLng)

                title?.text = poiItem.title
                var layout = view?.findViewById<LinearLayout>(R.id.id_ll_detail)
                layout?.visibility = View.VISIBLE

                var distanceTv = view?.findViewById<TextView>(R.id.id_tv_distance)
                var address = view?.findViewById<TextView>(R.id.id_tv_address)

                var distance = AMapUtils.calculateLineDistance(LatLng(curLat, curLng), targetLatLng)

                if (distance > 1000) {
                    var df = DecimalFormat("#.0")
                    distance = distance / 1000f

                    var label = "距您" + df.format(distance) + "公里"
                    distanceTv?.text = label
                }  else {
                    var label = "距您" + Math.round(distance) + "米"
                    distanceTv?.text = label
                }

                address?.text = poiItem?.snippet

                intent.putExtra(Constants.EXTRA_CURRENT_LAT, MapActivity.curLat)
                intent.putExtra(Constants.EXTRA_CURRENT_LNG, MapActivity.curLng)
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, MapActivity.curCity)
                intent.putExtra(Constants.EXTRA_POI, Poi(poiItem.title, LatLng(poiItem.latLonPoint.latitude, poiItem.latLonPoint.longitude), poiItem.poiId))
            }
        } else {
            title?.text = selectedPoi?.name
            markOptions.position(selectedPoi?.coordinate)

            intent.putExtra(Constants.EXTRA_CURRENT_LAT, MapActivity.curLat)
            intent.putExtra(Constants.EXTRA_CURRENT_LNG, MapActivity.curLng)
            intent.putExtra(Constants.EXTRA_CURRENT_CITY, MapActivity.curCity)
            intent.putExtra(Constants.EXTRA_POI, Poi(selectedPoi?.name, selectedPoi?.coordinate, selectedPoi?.poiId))
        }

        startIntent = intent

        markOptions.icon(BitmapDescriptorFactory.fromView(view))
        poiMarker = aMap.addMarker(markOptions)

        var cu = CameraUpdateFactory.changeLatLng(poiMarker?.position)
        aMap.moveCamera(cu)
    }

    var poiItemList: ArrayList<PoiItem> = arrayListOf()
    lateinit var potlistAdapter: PotListAdapter
    override fun onPoiSearched(result: PoiResult?, rCode: Int) {
        dismissDialog()
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.query != null) {
                useMoveToLocationWithMapMode = false
                poiResult = result
                if (result.query.equals(query)) {
                    Log.d("wqj", result.pois[0].title)
                    var poiItems: List<PoiItem> = result.pois
                    if (poiItems != null && poiItems.size > 0) {
                        aMap.clear()
                        aMap.addMarker(locationMarker?.options)
                        poiItems.forEach {
                            poiItemList.add(it)
                        }

                        listView.setAdapter(potlistAdapter)
                        if (poiCurrentPage == 1) {
                            //sliding_layout.setAnchorPoint(0.3f)
                            //sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.ANCHORED)
                            sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED)
                            slidingTitle.setText("收起")
                            searchLayout.visibility = View.GONE
                        }
                        potlistAdapter.notifyDataSetChanged()
                        //listView.setSelection(potlistAdapter.getCount()-10)
                        listView.setLoadCompleted()
                        var poiOverlay: PoiOverlay = PoiOverlay(aMap, poiItems)
                        poiOverlay.removeFromMap()
                        poiOverlay.addToMap()
                        poiOverlay.zoomToSpan()
                    } else {
                        ToastUtil.show(this, "没有找到相关poi信息")
                    }
                }
            } else {
                ToastUtil.show(this, "没有找到相关poi信息")
            }
        } else {
            ToastUtil.showerror(this, rCode)
        }
    }
    // end --- POI 检索回调

//    fun EnterPotEditMode(flag: Boolean) {
//        if (flag) {
//            Log.d("wqj", "comp gone")
//            /*
//            map.visibility = View.GONE
//            carInfo.visibility = View.GONE
//            routeSearchBtn.visibility = View.GONE
//            id_iv_currentLocation.visibility = View.GONE
//            id_iv_setLocation.visibility = View.GONE
//            */
//            map.alpha = 0f
//            carInfo.alpha = 0f
//            routeSearchBtn.alpha = 0f
//            id_iv_currentLocation.alpha = 0f
//            id_iv_setLocation.alpha = 0f
//            slidingTitle.alpha = 0f
//
//        } else {
//            Log.d("wqj", "comp visible")
//            /*
//            map.visibility = View.VISIBLE
//            carInfo.visibility = View.VISIBLE
//            routeSearchBtn.visibility = View.VISIBLE
//            id_iv_currentLocation.visibility = View.VISIBLE
//            id_iv_setLocation.visibility = View.VISIBLE
//            */
//            map.alpha = 1f
//            carInfo.alpha = 1f
//            routeSearchBtn.alpha = 1f
//            id_iv_currentLocation.alpha = 1f
//            id_iv_setLocation.alpha = 1f
//            if (!potlistAdapter.isEmpty) {
//                slidingTitle.alpha = 1f
//            }
//        }
//    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (sliding_layout.panelState == SlidingUpPanelLayout.PanelState.EXPANDED) {
            when (keyCode) {
                KeyEvent.KEYCODE_BACK -> {
                    sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED)

                    return true
                }
            }
        }

        return super.onKeyDown(keyCode, event)

    }

    fun doSearchQuery(keyword : String, around : Boolean) {

        showDialog()
        poiCurrentPage = 1
        poiItemList.clear()

        query = PoiSearch.Query(keyword, "", curCity)
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(poiCurrentPage);//设置查询页码

        var poiSearch = PoiSearch(this, query)
        poiSearch.setOnPoiSearchListener(this)
        if (around) {
            poiSearch.bound = PoiSearch.SearchBound(LatLonPoint(curLat, curLng), 5000, true)
        }
        poiSearch.searchPOIAsyn()

    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        Log.d("wqj", "hello searched: " + actionId)
        if(actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 隐藏软件盘
            var imm = v?.getContext()?.getSystemService(Context.INPUT_METHOD_SERVICE)
                        as InputMethodManager
            if(imm.isActive()) {
                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0)
            }
            showDialog()
            // potSearch(potSearchText.text.toString())
            poiCurrentPage = 1
            poiItemList.clear()
            poiSearch(potSearchText.text.toString())

            //EnterPotEditMode(false)
        }
        return true
    }
    // list view 下拉刷新
    override fun onloadMore() {
        if (poiResult.getPageCount() <= poiCurrentPage) {
            listView.setLoadFinished()
            return
        }
        Log.d("wqj", "Load more")
        poiCurrentPage++

        poiSearch(potSearchText.text.toString())
    }

    override fun onStart() {
        super.onStart()

        if (!isServcieBond) {
            val intent = Intent(this, NMEAParserService::class.java)
            isServcieBond = bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        Log.e(TAG, "onDestroy")
        //btReadThread.cancel()
        mMapView.onDestroy()

        if (mNMEAParserService != null) {
            mNMEAParserService!!.setOnInfoUpdateListener(null)
        }
    }

    override fun onResume() {
        super.onResume()
        //btReadThread.start()
        mMapView.onResume()

        useMoveToLocationWithMapMode = true
    }

    override fun onPause() {
        super.onPause()
       //btReadThread.cancel()
        mMapView.onPause()

        useMoveToLocationWithMapMode = false
    }

    override fun onStop() {
        super.onStop()
//        btReadThread.cancel()

        if (isServcieBond) {
            unbindService(mServiceConnection)
            isServcieBond = false
        }
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState)
    }

    private var isServcieBond = false
    private var mNMEAParserService: NMEAParserService? = null
    private val mServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(componentName: ComponentName, service: IBinder) {
            Log.e(TAG, "onServiceConnected")
            mNMEAParserService = (service as NMEAParserService.LocalBinder).service

            if (mNMEAParserService != null) {
                mNMEAParserService!!.setOnInfoUpdateListener(this@MapActivity)
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            Log.e(TAG, "onServiceDisconnected")
            mNMEAParserService = null
        }
    }

    override fun onRMCUpdate(position: NMEA.GPSPosition?) {

    }

    override fun onGGAUpdate(position: NMEA.GPSPosition?) {
        android.util.Log.e(TAG, position.toString())
        if (position != null) {
            onMyLocationChanged(position.lat, position.lon)
        }
    }

    override fun onAHRSUpdate(position: NMEA.GPSPosition?) {

    }

    override fun onGSVUpdate(svList: java.util.ArrayList<NMEA.SVInfo>?) {

    }


    fun initMapUi(mUiSettings: UiSettings) {
        // 设置默认定位按钮是否显示，非必需设置。
        mUiSettings.setMyLocationButtonEnabled(false)
        // 设置缩放按钮是否显示
        mUiSettings.setZoomControlsEnabled(false)
        // 指南针是否显示
        mUiSettings.setCompassEnabled(false);
    }

    fun showDialog() {
        loadingDialog?.show(getFragmentManager(), "Loading")
    }

    fun dismissDialog() {
        loadingDialog?.dismiss()
    }

    // 地址到坐标的转换
    fun potSearch(text: String) {
        // name表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
        val query = GeocodeQuery(text, curCity);
        geocoderSearch.getFromLocationNameAsyn(query);
    }

    // 经纬度转地址
    fun getAddress(lat: Double, lng: Double) {
		//showDialog()
		var query = RegeocodeQuery(LatLonPoint(lat, lng), 200f,
				GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
	}

    // poi检索
    fun poiSearch(text: String) {
        query = PoiSearch.Query(text, "", curCity)
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(poiCurrentPage);//设置查询页码

        var poiSearch = PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();
    }

    fun hideSoftKeyBoard(v: TextView?) {
        // 隐藏软件盘
        var imm = v?.getContext()?.getSystemService(Context.INPUT_METHOD_SERVICE)
                as InputMethodManager
        if(imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0)
        }
    }

    companion object {
        var curLat: Double = 31.221989  // AMap Coordinate
        var curLng: Double = 121.635006 // AMap Coordinate
        var curCity: String = "上海"
        var isRestrict: Boolean = false
    }

}
